package tw.BBT.BasalBodyTemperature.Components.DataStructs;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

import tw.BBT.BasalBodyTemperature.BasalBodyTemperature;
import android.widget.Toast;

public class TemperatureHistoryStatue {
	
	Date SelectedDate;
	SimpleDateFormat SDF;
	BasalBodyTemperature BBT;
	int Year,Month,Day,PageNum,CurrPage;
	
	public TemperatureHistoryStatue(BasalBodyTemperature BBT) {
		this.BBT = BBT;
		SelectedDate = new Date();
		UpdateStatue();
	}
	
	public void setDate(Date SelectedDate) {
		this.SelectedDate = SelectedDate;
		UpdateStatue();
	}
	
	public void UpdateStatue() {
		
		SDF =  new SimpleDateFormat("yyyy");
		Year = Integer.parseInt(SDF.format(SelectedDate));
		
		SDF =  new SimpleDateFormat("MM");
		Month = Integer.parseInt(SDF.format(SelectedDate));
		
		SDF =  new SimpleDateFormat("dd");
		Day = Integer.parseInt(SDF.format(SelectedDate));	
		
		CurrPage = Day/7;
		
		if(Month==2 && isBissextile(String.valueOf(Year))) {
			// 28-days: 28/7 (7day per page) =4(page)
			PageNum = 4;
		} else {
			PageNum = 5;
		}
		Toast.makeText(BBT,"( "+CurrPage+" / "+PageNum+" )" , Toast.LENGTH_LONG).show();
	}
	
    // ****************************************************************************
    // * 計算兩日期區間差異回傳天數*//
	// * ref: http://www.javaworld.com.tw/jute/post/view?bid=5&id=192195&tpg=1&ppg=1&sty=1&age=0
    // ****************************************************************************
    private static long calcutePeriod(String dateStr1,String dateStr2) {
        SimpleDateFormat sdf =  new SimpleDateFormat("yyyyMMdd");
        ParsePosition pos1 = new ParsePosition(0);
        ParsePosition pos2 = new ParsePosition(0);
        java.util.Date date1= sdf.parse(dateStr1,pos1);
        java.util.Date date2= sdf.parse(dateStr2,pos2);
        long dateDiff = 0;
        if(date1.getTime()<date2.getTime()) {
            dateDiff = ((date2.getTime()/1000-date1.getTime()/1000)/(24*60*60));
        }
        else {
            dateDiff = ((date1.getTime()/1000-date2.getTime()/1000)/(24*60*60));
        }
        return dateDiff;
    }
	
    // ****************************************************************************
    // * 回傳是否閏年 *// base_year = yyyy
    // * ref: http://www.javaworld.com.tw/jute/post/view?bid=5&id=192195&tpg=1&ppg=1&sty=1&age=0
    // ****************************************************************************
    private static boolean isBissextile(String base_year) {        
        boolean checkIsBissextile = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        ParsePosition pos1 = new ParsePosition(0);
        String base_year_0228 = base_year +"0228";
        String base_year_0301 = base_year +"0301";
        if(calcutePeriod(base_year_0228,base_year_0301)==2) checkIsBissextile = true;
        return checkIsBissextile;
    }	
}
